import Vue from 'vue'

const state = {
  employees: []
}

// 获取数据
const getters = {
  getEmployees: state => {
    return state.employees
  }
}

// 转变 更新数据
const mutations = {
  muEmployees (state, payload) {
    state.employees = payload.res
  }
}

// 获取数据
const actions = {
  findDepartment ({commit}, payload) {
    return new Promise((resolve) => {
      Vue.prototype.$DesignDB.findDepartment(payload.searchKey, function (department) {
        resolve(department[0])
      })
    })
  },
  searchEmployee ({commit}, payload) {
    return new Promise((resolve) => {
      let coId = Vue.prototype.$store.getters.currentUser.coId
      Vue.prototype.$DesignDB.findEmployees(coId, payload, function (employees) {
        commit({
          type: 'muEmployees',
          res: employees
        })
        resolve(employees)
      })
    })
  },
  // 查询多个员工
  async searchEmployees ({commit}, payload) {
    let employees = []
    const findEmployee = item => new Promise((resolve) => {
      let coId = Vue.prototype.$store.getters.currentUser.coId
      Vue.prototype.$DesignDB.findEmployees(coId, {mid: item.mid}, function (employee) {
        resolve(employee)
      })
    })
    for (let i = 0; i < payload.items.length; i++) {
      const arr = await findEmployee(payload.items[i])
      employees = [...employees, ...arr]
    }
    commit({
      type: 'muEmployees',
      res: employees
    })
  },
  findEmployee ({commit}, payload) {
    return new Promise((resolve) => {
      let coId = Vue.prototype.$store.getters.currentUser.coId
      Vue.prototype.$DesignDB.findEmployees(coId, payload, function (employees) {
        resolve(employees[0])
      })
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
